package spider

import (
	"context"
	"encoding/json"
)

type BinanceGetPosEarnListService struct {
	c         *Client
	asset     *string
	pageIndex *int
	pageSize  *int
}

type BinanceGetPosEarnListResponse struct {
	Code    string          `json:"code"`
	Data    json.RawMessage `json:"data"`
	Total   int             `json:"total"`
	Success bool            `json:"success"`
}

type BinanceAssetPosEarnInfo struct {
	Asset    string               `json:"asset"`
	Projects []BinancePosEarnInfo `json:"projects"`
}

type BinancePosEarnInfo struct {
	Asset     string               `json:"asset"`
	UpLimit   string               `json:"upLimit"`
	Purchased string               `json:"purchased"`
	Duration  string               `json:"duration"`
	Config    BinancePosEarnConfig `json:"config"`
	SellOut   bool                 `json:"sellOut"`
}

type BinancePosEarnConfig struct {
	AnnualInterestRate       string `json:"annualInterestRate"`
	DailyInterestRate        string `json:"dailyInterestRate"`
	MinPurchaseAmount        string `json:"minPurchaseAmount"`
	MaxPurchaseAmountPerUser string `json:"maxPurchaseAmountPerUser"`
}

func (s *BinanceGetPosEarnListService) Asset(v string) *BinanceGetPosEarnListService {
	s.asset = &v
	return s
}

func (s *BinanceGetPosEarnListService) PageIndex(v int) *BinanceGetPosEarnListService {
	s.pageIndex = &v
	return s
}

func (s *BinanceGetPosEarnListService) PageSize(v int) *BinanceGetPosEarnListService {
	s.pageSize = &v
	return s
}

func (s *BinanceGetPosEarnListService) Do(ctx context.Context, opts ...RequestOption) (res []*BinanceAssetPosEarnInfo, err error) {
	r := &request{
		method:   "GET",
		endpoint: "/bapi/earn/v1/friendly/pos/union",
	}
	m := params{}
	m["status"] = "ALL"
	if s.asset != nil {
		m["asset"] = *s.asset
	}
	if s.pageIndex != nil && s.pageSize != nil {
		m["pageIndex"] = *s.pageIndex
		m["pageSize"] = *s.pageSize
	}
	r.setParams(m)
	data, err := s.c.callAPI(ctx, r, opts...)
	if err != nil {
		return nil, err
	}
	resp := new(BinanceGetPosEarnListResponse)
	err = json.Unmarshal(data, resp)
	if err != nil {
		return nil, err
	}
	res = make([]*BinanceAssetPosEarnInfo, 0)
	err = json.Unmarshal(resp.Data, &res)
	if err != nil {
		return nil, err
	}
	return res, nil
}
